//
//  UITableViewController+HDOwnerInformation.m
//  app
//
//  Created by D on 15/5/6.
//  Copyright (c) 2015年 hdaren. All rights reserved.
//

#import "HDOwnerInformation.h"
#import "SNOrderFormListViewController.h"
#import "HDAddressController.h"
#import "HDProvinceCityController.h"
#import "HDHeaderModel.h"
#import "HDChatLIstController.h"
#import "HDMoreInformation.h"
#import "HDAboutUs.h"
#import "HDOpinion.h"
#import "HDGoodsCollectController.h"
#import "HDSignView.h"
#import "HDAlwaysQuestionController.h"
#import "HDContentTenementController.h"
#import "HDMyCommunityController.h"
#import "HDLoginoutViewController.h"

#import "HZGoodsSalesViewController.h"

static CGFloat kViewWight = 200.0f;
static CGFloat kViewHight = 160.0f;
static const CGFloat kRedPointH = 20.0f;


@implementation  HDOwnerInformation

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
//    self.navigationController.navigationBar.hidden = YES;

    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleDefault];
    
    
    
    if (![SNTool shouldLoginFromController:self]) {
        [self.tableView reloadData];
    }
    
    [self sendInformationResult];
    
    
}


- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.onwerInfo_result = [JKRemoteResult target:self action:@selector(infoData:)];
    self.result_logout = [JKRemoteResult target:self action:@selector(loginOut:)];
    self.signIn = [JKRemoteResult target:self action:@selector(signIn:)];
    
//    self.title = @"个人中心";
    if ([[NSUserDefaults standardUserDefaults]objectForKey:@"uid"]> 0) {
        self.dict = [NSDictionary dictionary];
        self.isAlreadyRed = NO;
        self.pmidArr = [NSMutableArray array];
        self.cellNames = @[@"1",@"全部订单"];
        self.cellImages = @[@"1",@"all_order"];
        
        DLog(@"%@",[[NSUserDefaults standardUserDefaults] objectForKey:@"uid"]);
        
        UIButton * chatBtn = [[UIButton alloc] initWithFrame:CGRectOf([self.ubo fx:1 ox:20 fy:0],
                                                                      [self.ubo ow:40 oh:40])];
        [chatBtn setImage:[UIImage imageNamed:@"chat_gz"] forState:UIControlStateNormal];
        chatBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
        [chatBtn addTarget:self action:@selector(rightBarBtnClicked:) forControlEvents:UIControlEventTouchUpInside];
        self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:chatBtn];
    }
    
    
    
    

    
    
}

-(void)rightBarBtnClicked:(UIButton*)sender
{
    HDChatLIstController * chatList = [[HDChatLIstController alloc]init];
    chatList.hidesBottomBarWhenPushed = YES;
    if ([[[NSUserDefaults standardUserDefaults]objectForKey:@"firstChat"]integerValue] == 0) {
        chatList.chatSign = @"0";
    }else
    {
        chatList.chatSign = @"1";
    }
    
    if (self.isAlreadyRed == NO) {
        chatList.tempPmids = self.pmidArr;
    }
    
    [self.navigationController pushViewController:chatList animated:YES];
}
//********

-(void)removeCellRed
{
    [self.redPoint setHidden:YES];
     [self.tableView reloadData];
   
}
-(void)addChatRedPoint:(NSNotification*)info
{
    if (self.headerView.btn.tag == 3) {
        self.redPoint = [[UIImageView alloc]initWithFrame:CGRectOf([self.headerView.btn.ufo fx:1 ux:-kRedPointH-12 fy:UB_1_2 uy:-kRedPointH*2], [self.ubo uw:kRedPointH uh:kRedPointH])];
        self.redPoint.backgroundColor = [UIColor orangeColor];
        self.redPoint.layer.masksToBounds = YES;
        self.redPoint.layer.cornerRadius = self.redPoint.bounds.size.width/2;
        [self.redPoint setHidden:NO];
        [self.headerView addSubview:self.redPoint];
        
        
        NSDictionary *pmidDictionary = [info userInfo];
        NSMutableArray * pmidArr = [pmidDictionary objectForKey:@"tempPmid"];
        self.pmidArr = pmidArr;
        [self.tableView reloadData];
        
       
    }
    
}
-(void)removeOnePageRed
{
    [self.redPoint setHidden:YES];
    
}

-(void)isAlreadyRedOn
{
    self.isAlreadyRed = YES;
}
//*******



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
#pragma mark - 请求个人信息
-(void)sendInformationResult
{
    HDUserInforHttpRequestManger * httpManager = [HDUserInforHttpRequestManger shareUserInforHttpRequestManger];
    [httpManager getUserInfoWithParams:nil result:self.onwerInfo_result];
}
#pragma mark - 数据处理
-(void)infoData:(JKRemoteResult*)result
{
//    [self.tableView endRefreshingAll];
    if (result.success) {
//        [self.tableView.nothingRefreshView remove];
//        [self.tableView reloadData];
        
        
        
        [[NSUserDefaults standardUserDefaults]setObject:[result.info objectForKey:@"scores"] forKey:@"scores"];
        [[NSUserDefaults standardUserDefaults]synchronize];
        
        
    }
    
    
    /*
    
//    result.info
    self.dict = result.info;
    [[NSUserDefaults standardUserDefaults] setObject:@"1" forKey:@"isLogin"];
    [[NSUserDefaults standardUserDefaults] setObject:self.dict forKey:@"udict"];
    [[NSUserDefaults standardUserDefaults] synchronize];
    HDHeaderModel * model = [[HDHeaderModel alloc]initWithDict:self.dict];
    self.headerView = [[HDHeaderView alloc]initWithUid:[NSString stringWithFormat:@"%d",[[[NSUserDefaults standardUserDefaults] objectForKey:@"uid"]integerValue]] Model:model];
    self.headerView.deletageHV = self;
    self.tableView.tableHeaderView = self.headerView;
    [self.tableView reloadData];
    
    [self everyDaySign];
    
    [self notificatRed];

     */
     
}

#pragma mark - 每天签到
-(void)everyDaySign
{
    //    获取当前时间
    NSTimeInterval time = [[NSDate date]timeIntervalSince1970];
    long long int currDate = (long long int)time;
    self.timeStr = [NSString stringWithFormat:@"%lld",currDate];
    //    取出保存时间获得保存时间与当前时间的差
    long long int savetiem  = [[[NSUserDefaults standardUserDefaults]objectForKey:@"signtime"] integerValue];
    NSDate  *datetime = [[NSDate alloc]initWithTimeIntervalSinceNow:savetiem];
    
    if (currDate - savetiem > 86400 || !savetiem) {
        
        //签到
        HDUserInforHttpRequestManger * httpManager = [HDUserInforHttpRequestManger shareUserInforHttpRequestManger];
        [httpManager signInWithResult:self.signIn];
       
    }


}


#pragma mark - 签到数据处理
-(void)signIn:(JKRemoteResult*)rt
{
    if (rt.failure) {
        UIAlertView * av = [[UIAlertView alloc]initWithTitle:nil message:@"请检查网络" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [av show];
        
        return;
    }else
    {
        if (rt.response.status == 0) {
            
            HDSignView * signView = [[HDSignView alloc]initWithDic:rt.content Frame:CGRectOf([self.ubo fx:UB_1_2 ux:-kViewWight/2 fy:UB_1_2 uy:-kViewHight/2], [self.ubo uw:kViewWight uh:kViewHight])];
            
            [self.tableView addSubview:signView];
            [self performSelector:@selector(dimissAlert:) withObject:signView afterDelay:2.0];
            
            [[NSUserDefaults standardUserDefaults] setObject:self.timeStr forKey:@"signtime"];
            [[NSUserDefaults standardUserDefaults] synchronize];
            
            
        }
        
    }
    
    
    
}
#pragma mark - 签到view 消失
- (void) dimissAlert:(HDSignView *)alert {
    if(alert)     {
        
        [alert removeFromSuperview];
        
    }
}

-(void)notificatRed
{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(removeCellRed) name:@"removeCellRed" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(addChatRedPoint:) name:@"redChatPoint" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(removeOnePageRed) name:@"removeOnePageRed" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(isAlreadyRedOn) name:@"isAreadyRed" object:nil];
}


#pragma mark - tableview
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    return 4;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // Return the number of rows in the section.
    if (section == 1) {
        return 5;
    }
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSUInteger section = [indexPath section];
    static NSString *CellIdentifier = @"HDOwnerCell";
    HDOwnerCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (section == 0) {
        
        cell = [[HDOwnerCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier Sign:1 Row:indexPath.row Uid:[[NSUserDefaults standardUserDefaults]objectForKey:@"uid"]];
//        cell.name.text = [self.cellNames objectAtIndex:[indexPath row]];
        cell.delegate = self;
//        [cell.image setImage:[UIImage imageNamed:[self.cellImages objectAtIndex:[indexPath row]]]];
        [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
    }
    else if (section == 1){

        cell = [[HDOwnerCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier Sign:2 Row:indexPath.row Uid:[[NSUserDefaults standardUserDefaults]objectForKey:@"uid"]];
        
        if (indexPath.row > 0) {
            [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
        }
        
//        [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
        cell.delegate = self;

    }
    else if (section == 2){
        cell = [[HDOwnerCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier Sign:3 Row:indexPath.row Uid:[[NSUserDefaults standardUserDefaults]objectForKey:@"uid"]];
        [cell setAccessoryType:UITableViewCellAccessoryNone];
        cell.delegate = self;
        [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
    }
    else if (section == 3){
        
        cell = [[HDOwnerCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier Sign:4 Row:indexPath.row Uid:[[NSUserDefaults standardUserDefaults]objectForKey:@"uid"]];
        [cell setAccessoryType:UITableViewCellAccessoryNone];
        cell.backgroundColor = [UIColor clearColor];
        cell.delegate = self;
        
    }
    
    
    return cell;
}
 - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([indexPath section] == 0 && indexPath.row == 0 ) {
        return 72;
    }else if ([indexPath section] == 1 && indexPath.row ==0){
        return 64;
    }
    return 44;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSUInteger section=[indexPath section];

        switch (section) {
            
            case 1:
            {
                switch ([indexPath row]) {
                    case 1:
                    {
                       
                            //联系物业
                        self.navigationController.navigationBar.hidden = NO;
                            HDContentTenementController * opinion = [self.storyboard instantiateViewControllerWithIdentifier:@"content"];
                            opinion.hidesBottomBarWhenPushed = YES;
                            [self.navigationController pushViewController:opinion animated:YES];
                        
                       

                    }
                        break;
                    case 2:
                    {
                        //我的小区
                        self.navigationController.navigationBar.hidden = NO;
                        HDMyCommunityController * alwaysQuestion = [[HDMyCommunityController alloc]init];
                        
                        alwaysQuestion.hidesBottomBarWhenPushed = YES;
                        [self.navigationController pushViewController:alwaysQuestion animated:NO];
                        
                        
                    }
                        break;
                    case 3:
                    {
                        //考拉之家客服
                        NSString * phoneNumber = [NSString stringWithFormat:@"telprompt:03513077866"];
                        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:phoneNumber]];
                        
                        
                    }
                        break;
                
                    case 4:
                    {
                        //消息中心
                        if ([[[NSUserDefaults standardUserDefaults]objectForKey:@"uid"]integerValue] > 0) {
                            
                            if ([[[NSUserDefaults standardUserDefaults]objectForKey:@"huodong_url"]length] > 0) {
                                //跳转页面
                                HZGoodsSalesViewController *salesVC = [[HZGoodsSalesViewController alloc] init];
                                salesVC.webTitle = @"活动";
                                salesVC.webURL = [NSString stringWithFormat:@"%@uid=%@",[[NSUserDefaults standardUserDefaults]objectForKey:@"huodong_url"],[[NSUserDefaults standardUserDefaults]objectForKey:@"uid"]];
                                salesVC.hidesBottomBarWhenPushed = YES;
                                [self.navigationController pushViewController:salesVC animated:YES];
                                
                            }else
                            {
                                [MyToast showWithText:@"暂无消息"];
                            }
                            
                        }else
                        {
                            [MyToast showWithText:@"暂无消息"];
                        }
                        
                        
                        
                    }
                        
                        
                    default:
                        break;
                }
            }
                break;
                
            default:
                break;
        }

    
    
        [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    return nil;
}

#pragma mark - headerView 高度
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
//    if (section == 0) {
//        return 16;
//    }else
    return 10;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
   
    return 0.1;
}

//- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
//{
//    if (section == 1) {
//        
//        HDWaiterView * waiterView = [[HDWaiterView alloc]initToFrame];
////        waiterView.backgroundColor = [UIColor redColor];
//        return waiterView;
//        
//    }else{
//       return nil;
//    }
//    
//}



#pragma mark - headerView delegate
-(void)headerViewSelectLoginOutHeader
{
    if ([[[NSUserDefaults standardUserDefaults]objectForKey:@"uid"]integerValue] == 0) {
//        [self.navigationController setNavigationBarHidden:NO];
        self.navigationController.navigationBar.hidden = NO;
        HDAppDelegate* app = (HDAppDelegate*)[[UIApplication sharedApplication]delegate];
        app.storyBoard = [UIStoryboard storyboardWithName:@"LogInOutStoryboard" bundle:nil];
        
        UIViewController * loginOut = [app.storyBoard instantiateViewControllerWithIdentifier:@"login"];
        loginOut.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:loginOut animated:NO];
        
    }else
    {
        
        self.progress_ = [[MBProgressHUD alloc]initWithView:self.view];
        [self.view addSubview:self.progress_];
        [self.view bringSubviewToFront:self.progress_];
        self.progress_.delegate = self;
        self.progress_.labelText = @"正在退出中...";
        [self.progress_ show:YES];
        
        HDUserInforHttpRequestManger * httpManager = [HDUserInforHttpRequestManger shareUserInforHttpRequestManger];
        NSDictionary * params = @{@"version":APP_VERSION};
        [httpManager loginOutWithParams:params result:self.result_logout];

        
    }
}
-(void)clickHeaderJumpMoreInformation:(UIButton *)sender
{
    if ([[[NSUserDefaults standardUserDefaults]objectForKey:@"uid"]integerValue] != 0) {
        self.navigationController.navigationBar.hidden = NO;
        UIStoryboard * storyBoard = [UIStoryboard storyboardWithName:@"MainStoryBoard" bundle:nil];
        HDMoreInformation * moreView = [storyBoard instantiateViewControllerWithIdentifier:@"more"];
        moreView.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:moreView animated:NO];
    
    }
}
#pragma mark - 退出账号
-(void)loginOut:(JKRemoteResult*)rt
{
    
    if (self.progress_) {
        [self.progress_ removeFromSuperview];
        self.progress_ = nil;
    }
    
    if (rt.failure) {
        UIAlertView * av = [[UIAlertView alloc]initWithTitle:nil message:@"请检查网络" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [self.view addSubview:av];
        [av show];
        
        return;
    }
    //    [self.navigationController setNavigationBarHidden:NO];
    
    NSString * uid = [[NSUserDefaults standardUserDefaults] objectForKey:@"uid"];
    NSString * allInformation = [[NSBundle mainBundle] bundleIdentifier];
    [[NSUserDefaults standardUserDefaults]removePersistentDomainForName:allInformation];
    
    [[SDImageCache sharedImageCache]removeImageForKey:@"user_Head"];
    
    
    
    [[NSUserDefaults standardUserDefaults] setObject:uid forKey:@"mark"];
    [[NSUserDefaults standardUserDefaults] synchronize];
    
    HDAppDelegate* app = (HDAppDelegate*)[[UIApplication sharedApplication]delegate];
    
    app.storyBoard = [UIStoryboard storyboardWithName:@"MainStoryBoard" bundle:nil];
    //        [self presentViewController:[app.storyBoard instantiateInitialViewController] animated:NO completion:nil];
    app.window.rootViewController = [app.storyBoard instantiateInitialViewController];
    [app.window makeKeyAndVisible];

}

-(void)clickHeaderBtnFrom:(UIButton *)sender
{
    switch (sender.tag) {
        case 1:
        {
            NSLog(@"商品收藏");
//            [self.navigationController setNavigationBarHidden:NO];
            self.navigationController.navigationBar.hidden = NO;
            HDGoodsCollectController * goodsCollect = [[HDGoodsCollectController alloc]init];
            //                            goodsCollect.actID = @"0";
            goodsCollect.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:goodsCollect animated:NO];
        }
            break;
        case 2:
        {
            NSLog(@"地址管理");
            self.navigationController.navigationBar.hidden = NO;
           
        }
            break;
        case 3:
        {
            NSLog(@"在线客服");
            HDChatLIstController * chatList = [[HDChatLIstController alloc]init];
            chatList.hidesBottomBarWhenPushed = YES;
            if ([[[NSUserDefaults standardUserDefaults]objectForKey:@"firstChat"]integerValue] == 0) {
                chatList.chatSign = @"0";
            }else
            {
                chatList.chatSign = @"1";
            }
            
            if (self.isAlreadyRed == NO) {
                chatList.tempPmids = self.pmidArr;
            }
            
            [self.navigationController pushViewController:chatList animated:NO];
            
            [[NSNotificationCenter defaultCenter] postNotificationName:@"removeCellRed" object:nil];
            [[NSNotificationCenter defaultCenter] postNotificationName:@"removePeoRedPoint" object:nil];
        
        }
            break;
            
        default:
            break;
    }
}



#pragma mark - 自定义Cell的delegate

-(void)cellSelectClickHeaderButtonWithButton:(UIButton *)sender
{
//    if ([[NSUserDefaults standardUserDefaults]objectForKey:@"uid"] && [[[NSUserDefaults standardUserDefaults]objectForKey:@"uid"] length] >0) {
//           }
    
    if (![[NSUserDefaults standardUserDefaults]objectForKey:@"uid"] && [[[NSUserDefaults standardUserDefaults]objectForKey:@"uid"] integerValue] == 0) {
  
        UIAlertView * av = [[UIAlertView alloc]initWithTitle:nil message:@"尚未登陆" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [self.view addSubview:av];
        [av show];
        
    }else
    {
        switch (sender.tag) {
            case 0:
            {
                NSLog(@"待支付");
//                [self.navigationController setNavigationBarHidden:NO];
                self.navigationController.navigationBar.hidden = NO;
                SNOrderFormListViewController * allOrderView = [[SNOrderFormListViewController alloc]init];
                allOrderView.style = OrderFormListWillPay;
                allOrderView.hidesBottomBarWhenPushed = YES;
                [self.navigationController pushViewController:allOrderView animated:NO];
            }
                break;
            case 1:
            {
                NSLog(@"待收货");
//                [self.navigationController setNavigationBarHidden:NO];
                self.navigationController.navigationBar.hidden = NO;
                SNOrderFormListViewController * allOrderView = [[SNOrderFormListViewController alloc]init];
                allOrderView.style = OrderFormListWillReceive;
                allOrderView.hidesBottomBarWhenPushed = YES;
                [self.navigationController pushViewController:allOrderView animated:NO];
            }
                break;
            case 2:
            {
                NSLog(@"带评价");
//                [self.navigationController setNavigationBarHidden:NO];
                self.navigationController.navigationBar.hidden = NO;
                SNOrderFormListViewController * allOrderView = [[SNOrderFormListViewController alloc]init];
                allOrderView.style = OrderFormListWillAppraise;
                allOrderView.hidesBottomBarWhenPushed = YES;
                [self.navigationController pushViewController:allOrderView animated:NO];
               
                
                
            }
                break;
            case 3:
            {
                NSLog(@"全部订单");
//                [self.navigationController setNavigationBarHidden:NO];
                self.navigationController.navigationBar.hidden = NO;
                SNOrderFormListViewController * allOrderView = [[SNOrderFormListViewController alloc]init];
                allOrderView.style = OrderFormListAll;
                allOrderView.hidesBottomBarWhenPushed = YES;
                [self.navigationController pushViewController:allOrderView animated:NO];
            }
                break;
                
            default:
                break;
        }
        
           }
    
   
 
}
-(void)loginout
{
    self.progress_ = [[MBProgressHUD alloc]initWithView:self.view];
    [self.view addSubview:self.progress_];
    [self.view bringSubviewToFront:self.progress_];
    self.progress_.delegate = self;
    self.progress_.labelText = @"正在退出中...";
    [self.progress_ show:YES];
    
    HDUserInforHttpRequestManger * httpManager = [HDUserInforHttpRequestManger shareUserInforHttpRequestManger];
    NSDictionary * params = @{@"version":APP_VERSION};
    [httpManager loginOutWithParams:params result:self.result_logout];
}


-(void)headerviewSelectChatList
{
    NSLog(@"点击了聊天列表");
}

-(void)headerviewSelectClickSet
{
    NSLog(@"点击了设置");
}


-(void)willPresentAlertView:(UIAlertView *)alertView
{
    NSLog(@"%d",alertView.subviews.count);
    for (UIView *tempView in alertView.subviews) {
        
        if ([tempView isKindOfClass:[UILabel class]]) {
           
            UILabel *tempLabel = (UILabel *) tempView;
            
            if ([tempLabel.text isEqualToString:alertView.message]) {
                
                [tempLabel setTextColor:[UIColor orangeColor]];
            
            }
        }
    }
}

@end













